package com.leetroll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leetroll.api.mapper.ChapterMapper;
import com.leetroll.api.service.ChapterDetailService;
import com.leetroll.api.service.ChapterService;
import com.leetroll.common.constant.SQLConstant;
import com.leetroll.common.entity.Chapter;
import com.leetroll.common.vo.ChapterDetailVO;
import com.leetroll.common.vo.ChapterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterServiceImpl extends SuperServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    private final ChapterDetailService chapterDetailService;

    @Autowired
    public ChapterServiceImpl(ChapterDetailService chapterDetailService) {
        this.chapterDetailService = chapterDetailService;
    }

    @Override
    @Cacheable(cacheNames = "getAllChapterByItemId", key = "#itemId")
    public List<ChapterVO> getAllByItemId(Long itemId) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.ITEM_ID, itemId);
        List<Chapter> chapters = this.list(queryWrapper);
        List<ChapterVO> vos = new ArrayList<>();
        chapters.forEach(chapter -> {
            ChapterVO vo = fromEntity(chapter);
            List<ChapterDetailVO> detailVOS = chapterDetailService.listByChapterId(chapter.getId());
            vo.setDetails(detailVOS);
            vos.add(vo);
        });
        return vos;
    }

    private ChapterVO fromEntity(Chapter chapter) {
        ChapterVO vo = new ChapterVO();
        vo.setId(chapter.getId());
        vo.setItemId(chapter.getItemId());
        vo.setTitle(chapter.getTitle());
        vo.setDesp(chapter.getDesp());
        vo.setChapter(chapter.getChapter());
        vo.setMain(chapter.getMain());
        return vo;
    }
}
